//
//  JSSComposePictureView.swift
//  WeiBoItem
//
//  Created by jss on 16/4/27.
//  Copyright © 2016年 jss. All rights reserved.
//

import UIKit
import SVProgressHUD
import SnapKit

class JSSComposePictureView: UICollectionView {
    
    
     //控制导航发送按钮状态的闭包(打开)
    var controlRingtItem:(()->())?
    
    //控制导航发送按钮状态的闭包(关闭 imagees的Count为0时关闭)
    var controlRingt:(()->())?
    
    
    //数组用来保存当前View显示的图片数据
    var images:[UIImage] = []
    
    //点击加号按钮 选择图片的闭包
    var selectedPictureClosure:(()->())?
    

        override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
    
            super.init(frame: frame, collectionViewLayout: layout)
    
            self.setupUI()
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    
        private func setupUI(){
    
        backgroundColor = UIColor.whiteColor()
    
            self.dataSource = self
            self.delegate = self
    
   // 注册cell
     registerClass(JSSComposePictureViewCell.self, forCellWithReuseIdentifier: "cell")
    
    
    
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            let margin :CGFloat = 5
            let itemW :CGFloat = (self.frame.width - 2 * margin) / 3
            let itemH :CGFloat = itemW
            
            //设置itemsize
            let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
            
            flowLayout.itemSize = CGSize(width: itemW, height: itemH)
            flowLayout.minimumInteritemSpacing = margin
            flowLayout.minimumLineSpacing = margin
            
            
        }
    
    //添加图片的方法
    func addImages(image:UIImage){
        
        if images.count < 9 {
            print(images.count)
            
            //回调控制导航发送按钮状态的闭包
            controlRingtItem!()
            
            images.append(image)
            //刷新数据
            self.reloadData()
        }else {
            //提示
            SVProgressHUD.showErrorWithStatus("你选择的图片以达上限")
            
        }
        
    }
    
    
    }

      //数据源方法的分类
    extension JSSComposePictureView : UICollectionViewDataSource,UICollectionViewDelegate{
    
    
        func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            //回调闭包(当图片数量为零时 ) //控制导航发送按钮状态的闭包(关闭 imagees的Count为0时关闭)
            if images.count == 0 {
                self.controlRingt!()
            }
            self.hidden = images.count == 0
            return images.count + ((images.count == 0 || images.count == 9) ? 0 : 1)
        }
    
        func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! JSSComposePictureViewCell
            
           // print(indexPath.item)
            
            
            if indexPath.item == images.count {
                //代表是最后一张加号按钮cell
              
                //cell.image = UIImage(named: "compose_pic_add")
                
                cell.image = nil
                
                
            }else{
                
                
                cell.image = images[indexPath.item]
            }
            
            //设置数据
           // cell.image = images[indexPath.item]
            
            //执行删除按钮的闭包
            cell.deleteBtnClosure = {
                
                //移除选中的图片
                self.images.removeAtIndex(indexPath.item)
                //刷新数据
                self.reloadData()
            
            }
            
            //cell.backgroundColor = randomColor
            
            return cell
        }
        
        //监听cell的点击
        func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
            
            if indexPath.item == images.count {
                
                //代表选择的是最后一个加号按钮cell
                //同样的cell没有监听点击cell的能力 所以要把这个点击实现的方法交给控制器执行
                //执行闭包
                self.selectedPictureClosure?()
                
            }
        }

}


//自定义cell的分类
class JSSComposePictureViewCell : UICollectionViewCell {
    
    //定义一个闭包 执行删除按钮的点击事件
    var deleteBtnClosure:(()->())?
    
    //添加一个image属性
    var image: UIImage? {
    
        didSet {
            
            if image == nil {
                
                imageView.image = UIImage(named: "compose_pic_add")
                //隐藏关闭按钮
                deleteBtn.hidden = true
            }else{
                
                imageView.image = image
                //显示关闭按钮
                deleteBtn.hidden = false
            }
            
        }
    
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func  setupUI() {
        
        //往cell的contentView上添加imageView
        contentView.addSubview(imageView)
        
        //把关闭按钮添加到cell的contentView上
        contentView.addSubview(deleteBtn)
        
        
        //约束imageView
        imageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView)
        }
        
        //约束closeBtn
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.trailing.equalTo(imageView)
        }
        
        
    }
    
    //关闭按钮的点击事件
    @objc private func didClickCloseBtn() {
    
        //执行闭包
        self.deleteBtnClosure?()
    }
    
    
    //懒加载imageView
    private lazy var imageView:UIImageView = UIImageView()
    
    private lazy var deleteBtn:UIButton = {
        
        let btn = UIButton()
        
        //给btn添加监听事件
        btn.addTarget(self, action: "didClickCloseBtn", forControlEvents: UIControlEvents.TouchUpInside)
        
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        return btn
    }()
    
}
